package com.project.harmonyledger.service.impl.user.account;

import com.project.harmonyledger.common.response.Result;
import com.project.harmonyledger.common.response.ResultCode;
import com.project.harmonyledger.mapper.UserMapper;
import com.project.harmonyledger.pojo.User;
import com.project.harmonyledger.service.user.account.InfoService;
import com.project.harmonyledger.utils.UserDetailsImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class InfoServiceImpl implements InfoService {
  @Autowired
  private UserMapper userMapper;

  @Override
  public Result<Map<String, String>> getInfo() {
    try {
      UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder
          .getContext().getAuthentication();

      UserDetailsImpl loginUser = (UserDetailsImpl) authentication.getPrincipal();
      User user = loginUser.getUser();

      Map<String, String> map = new HashMap<>();
      map.put("id", user.getId().toString());
      map.put("username", user.getUsername());
      map.put("nickname", user.getNickname());
      map.put("photo", user.getPhoto());

      return Result.success(map);

    } catch (Exception e) {
      log.error("获取用户信息失败: {}", e.getMessage());
      Map<String, String> map = new HashMap<>();
      map.put("message", ResultCode.UNAUTHORIZED.getMessage());
      return Result.error(ResultCode.UNAUTHORIZED, map);
    }
  }

  @Override
  public Result<Map<String, String>> updateUserInfo(String nickname, String photo) {
    Map<String, String> map = new HashMap<>();

    try {
      // 获取当前登录用户
      UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder
          .getContext().getAuthentication();
      UserDetailsImpl loginUser = (UserDetailsImpl) authentication.getPrincipal();
      User user = loginUser.getUser();

      // 更新用户信息
      if (nickname != null && !nickname.trim().isEmpty()) {
        user.setNickname(nickname.trim());
      }
      if (photo != null && !photo.trim().isEmpty()) {
        user.setPhoto(photo.trim());
      }
      user.setUpdatedAt(new Date());

      // 保存到数据库
      userMapper.updateById(user);

      // 返回更新后的信息
      map.put("id", user.getId().toString());
      map.put("username", user.getUsername());
      map.put("nickname", user.getNickname());
      map.put("photo", user.getPhoto());

      return Result.success(map);

    } catch (Exception e) {
      log.error("更新用户信息失败: {}", e.getMessage());
      map.put("message", "更新用户信息失败");
      return Result.error(ResultCode.SYSTEM_ERROR, map);
    }
  }
}
